from flask import session
from inc.models import AdminMember, OperationLog
from datetime import datetime
from .wechat import WechatAuth

def login_user(username, password, ip_address=None):
    """处理用户登录逻辑"""
    # 查找会员（支持用户名、手机号、邮箱登录）
    member = AdminMember.query.filter(
        (AdminMember.name == username) |
        (AdminMember.mobile == username) |
        (AdminMember.email == username)
    ).first()

    if not member or not member.check_password(password):
        # 记录失败的登录尝试
        OperationLog.create(
            admin_id=None,
            action="会员登录尝试",
            resource="Auth",
            details=f"失败的会员登录尝试，用户名: {username}",
            success=False,
            ip_address=ip_address
        )
        return None

    # 检查会员状态
    if not member.status:
        return None

    # 记录登录操作
    OperationLog.create(
        admin_id=None,
        action="会员登录",
        resource="Auth",
        details=f"会员 {member.name} 登录系统",
        success=True,
        ip_address=ip_address
    )

    return member

def logout_user(member_name, ip_address=None):
    """处理用户登出逻辑"""
    # 记录退出操作
    OperationLog.create(
        admin_id=None,
        action="会员退出",
        resource="Auth",
        details=f"会员 {member_name} 退出系统",
        success=True,
        ip_address=ip_address
    )

def wechat_login(state, code, config, ip_address=None):
    """企业微信扫码登录服务"""
    member = WechatAuth.handle_login_callback(state, code, config)
    if member:
        OperationLog.create(
            admin_id=None,
            action="企业微信扫码登录",
            resource="Auth",
            details=f"会员 {member.name} 通过企业微信登录",
            success=True,
            ip_address=ip_address
        )
    return member